package com.achen.workquene;

import com.achen.utils.RabbitMQUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author achen
 * @create 2021-07-25 4:22
 */
public class Customer2 {

    public static void main(String[] args) throws IOException {

        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();

        //获取通道对象
        Channel channel = connection.createChannel();

        //为了保证数据不丢失 每次接受一个消息 剩余的消息还在队列中保存
        channel.basicQos(1);

        //通过通道声明队列
        channel.queueDeclare("work", true, false, false, null);

        //消费消息
        channel.basicConsume("work", false, new DefaultConsumer(channel) {

            @lombok.SneakyThrows
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                Thread.sleep(1000);
                System.out.println("消费者2：" + new String(body));

                //手动确认 参数一：手动确认消息标识 参数二：false 每次确认一个
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}
